package org.basis.advance.c1;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * 短连接测试client
 *
 * @author Mr_wenpan@163.com 2021/09/20 10:38
 */
@Slf4j
public class ShortConnectClient {

    public static void main(String[] args) throws InterruptedException {

        // 循环10次向server发送10条消息，每发完一条就关闭channel。模拟短连接场景
        for (int i = 0; i < 10; i++) {
            send();
        }
        System.out.println("finish.");

    }

    private static void send() throws InterruptedException {
        NioEventLoopGroup woker = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.group(woker);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast(new ChannelInboundHandlerAdapter() {

                        // 会在连接channel建立成功后，会触发active事件
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            // 向服务端发送消息，发完消息就关闭channel
                            ByteBuf buf = ctx.alloc().buffer(16);
                            buf.writeBytes(new byte[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17});
                            ctx.writeAndFlush(buf);
                            ctx.channel().close();
                        }
                    });
                }
            });
            ChannelFuture channelFuture = bootstrap.connect(new InetSocketAddress("localhost", 8080)).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("client error ", e);
        } finally {
            woker.shutdownGracefully();
        }

    }
}
